<template>
  <a-card :bordered="false" :title="getTitle(type)">
    <div class="e e-base">
      <h3>基本资料</h3>
      <base-information :businessType="type" :taskId="taskId" :approvalNumber="approvalNumber" :jsonParam="jsonParam" />
    </div>
    <!--//结案评估、季度评估、年度评估、季度评估补录、年度评估补录-->
    <div class="e e-comments" v-if="type == 16 || type == 26 || type == 27 || type == 28 || type == 29">
      <h3>管控情况</h3>
      <control-service :business-type="type" :jsonParam="jsonParam" />
    </div>
    <!--//结案评估、访谈逾期补录、季度评估、年度评估、季度评估补录、年度评估补录-->
    <div class="e e-comments" v-if="type == 16 || type == 22 || type == 26 || type == 27 || type == 28 || type == 29">
      <h3>{{ type == 16 ? '结案信息' : type == 22 ? '谈话内容' : '评估情况' }}</h3>
      <other-information :business-type="type" :jsonParam="jsonParam" />
    </div>
    <!--// 16结案评估，45美沙酮入组、26季度评估、27年度评估、29季度评估补录、29年度评估补录-->
    <!--//美沙酮入组--入组信息：省级+卫健委-->
    <!--//季度评估、年度评估、季度评估补录、年度评估补录--办公室意见：省级+政法委-->
    <div class="e e-comments" style="position: relative;"
      v-if="(type == 16 || type == 45 || type == 26 || type == 27 || type == 28 || type == 29) && isLastHandle">
      <template v-if="type == 16">
        <!-- <template v-if="jsonParam.caseType == '1'">
          <h3>解除社区戒毒社区康复通知书编号</h3>
          <a-tooltip style="margin-left:10px;position: absolute;left: 252px;top: 32px;" placement="topLeft">
            <template slot="title">
              输入解除社区戒毒社区康复通知书编号，自动生成通知书。
            </template>
            <a-icon type="exclamation-circle" />
          </a-tooltip>
        </template> -->
      </template>
      <h3 v-else-if="type == 45">入组信息</h3>
      <h3 v-else>办公室意见</h3>
      <comments ref="commentsRefs" :business-type="type" :jsonParam="jsonParam" />
    </div>
    <div class="e e-steps">
      <h3>审批流程</h3>
      <!-- {{ isApprover }} -->
      <steps :approvalId="approvalId" :business-type="type" :status="status" :list="list" :isApprover="isApprover"
        :isWorkingInfo="isLastHandle" @urge="handleUrge" ref="examineStepsRefs" />
      <!--//status为1(待审批)时，才能提交审批-->
      <div style="margin-left:80px;" v-if="isApprover">
        <a-button type="primary" @click="onSubmit"> 确定 </a-button>
      </div>
    </div>
  </a-card>
</template>

<script>
import Vue from 'vue'
import { USER_INFO } from "@/store/mutation-types"
import * as flowServiceApi from '@/api/sjsk/flowService'
import baseInformation from './modules/baseInformation'
import otherInformation from './modules/otherInformation'
import comments from './modules/comments'
import controlService from './modules/controlService'
import steps from './modules/steps'
// import { validateDuplicateValue, alwaysResolve, failedSymbol } from '@/utils/util'
export default {
  inject: ['closeCurrent'],
  components: { baseInformation, controlService, otherInformation, comments, steps },
  data() {
    return {
      type: 0,
      typeName: null,
      status: null,
      taskId: null,
      approvalNumber: null,
      approvalId: null,
      approverId: null, // 发起人的userId
      jsonParam: {}, // 基本信息-对象
      list: [],
      processId: ""
    }
  },
  created() {
    this.getRouteQuery(this.$route)
  },
  watch: {
    $route(data) {
      this.getRouteQuery(data)
    },
    taskId(value) {
      if (this.processId) { //异常上报列表，查看跳转进来（特殊处理）
        this.getApprovalInfo()
      } else {
        this.getApprovalId()
      }

    },
  },
  computed: {
    // 是否需要审批
    isApprover() {
      if (this.status == 1) {
        return true
      } else {
        return false
      }
    },
    // 最后节点的审批人是否是当前审批人且是待审批状态
    isLastHandle() {
      let bool = false
      let userId = Vue.ls.get(USER_INFO).id //当前用户id
      let lastCol = this.list.length > 0 ? this.list[this.list.length - 1] : {}
      if (lastCol && Object.keys(lastCol).length > 0) {
        bool = (lastCol.approverId === userId) && (this.status === 1) ? true : false
      }
      return bool
    }
  },
  beforeRouteEnter: (to, from, next) => {
    // console.log(to)
    next(vm => {
      if (to.params.type == vm.type) {
        to.meta.title = vm.getTitle(vm.type) + '-审批详情';
      }
    })
  },
  methods: {
    // 审批详情信息
    async getApprovalId() {
      await flowServiceApi.getApprovalId({ taskId: this.taskId, type: this.type }).then(res => {
        if (res.success) {
          const { result } = res
          this.approvalId = result.id
          this.approvalNumber = result.approvalNumber
          this.jsonParam = result.jsonParam ? JSON.parse(result.jsonParam) : {}
          console.log(this.jsonParam);
          this.getProcessDetail(this.approvalId)
        }
      })
    },
    // 根据流程id获取审批详情信息
    getApprovalInfo() {
      flowServiceApi.getApprovalInfo(this.processId).then(res => {
        if (res.success) {
          const { result } = res
          this.approvalId = result.id
          this.approvalNumber = result.approvalNumber
          this.jsonParam = result.jsonParam ? JSON.parse(result.jsonParam) : {}
          this.getProcessDetail(this.approvalId)
        }
      })
    },
    // 查询流程详情
    getProcessDetail(approvalId) {
      if (!this.approvalId) return
      let userInfo = Vue.ls.get(USER_INFO)
      let userId = userInfo.id //当前用户id
      flowServiceApi.getProcessDetail(approvalId).then(res => {
        if (res.success) {
          this.list = res.result
          // console.log("userId")
          // console.log(userId)
          let arr = this.list.filter((col, i) => col.approverId === userId)
          let col = {}
          // console.log("arr")
          // console.log(arr)
          col = arr.find(obj => { return obj.status === 1 }) || {}
          // console.log("col")
          // console.log(col)
          if (arr && arr.length > 0) {
            if (col && Object.keys(col).length === 0) {
              col = arr[arr.length - 1]  //多个节点是一个审批人，则取最后一条记录
            }
            if (col && Object.keys(col).length > 0) {
              this.status = col.status
            }
          }
        } else {
          this.$message.warn(res.message)
        }
      })
    },
    // 提交审批
    onSubmit() {
      if (!this.approvalId) return
      if (this.onValidate()) return
      const { form } = this.$refs.examineStepsRefs
      this.$refs.examineStepsRefs.$refs.formRefs.validate((valid) => {
        if (valid) {
          // 添加入组信息(美沙酮入组)
          if (this.type == 45 && this.$refs.commentsRefs) {
            const { formData } = this.$refs.commentsRefs
            this.onSubmitApi(formData, 2)
          }
          // 添加办公室意见(季度评估、年度评估、季度评估补录、年度评估补录)
          if ((this.type == 26 || this.type == 27 || this.type == 28 || this.type == 29) && this.$refs.commentsRefs) {
            const { formData } = this.$refs.commentsRefs
            this.onSubmitApi(formData, 3)
          }
          // 结案评估(结案类型:期满解除)
          // if (this.type == 16 && this.jsonParam.caseType == '1' && this.$refs.commentsRefs) {
          //   const { formData } = this.$refs.commentsRefs
          //   formData.sjskId = this.jsonParam.spId
          //   this.onSubmitApi(formData, 4)
          // }
          // 提交审批
          this.onSubmitApi(form, 1)
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    // 提交审批、添加入组信息、添加办公室意见-接口
    onSubmitApi(form, type) {
      console.log(type)
      console.log(form)
      let status = form.status === 2 ? '通过' : '驳回'
      let api = ""
      if (type === 1) api = flowServiceApi.approval(form)//审批
      if (type === 2) api = flowServiceApi.updateMstPersonInfo(form) //添加入组信息
      if (type === 3) api = flowServiceApi.updateCompEvaluation(form)//添加办公室意见
      if (type === 4) api = flowServiceApi.jcsjsktzs(form)//结案评估(结案类型:期满解除)
      // let api = type === 1 ? flowServiceApi.approval(form) : type === 2 ? flowServiceApi.updateMstPersonInfo(form) : type === 3 ? flowServiceApi.updateCompEvaluation(form)
      //   : null
      // if (!api) return
      api.then(res => {
        if (res.success) {
          if (type == 1) {
            this.$message.success(res.message + status)
            this.handleCloseCurrentPage()
          }
        } else {
          this.$message.warn(res.message)
        }
      })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    // 入组信息和办公室意见-校验
    onValidate() {
      const { commentsRefs } = this.$refs
      let bool = false
      commentsRefs && commentsRefs.$refs.formRefs.validate((valid) => {
        if (valid) {
          bool = false
        } else {
          bool = true
        }
      })
      return bool
    },
    // 催一下
    handleUrge() {
      flowServiceApi.getUrge({ id: this.approvalId }).then(res => {
        if (res.success) {
          this.$message.success(res.message);
          let index = this.list.findIndex(item => item.status === 1)
          let obj = this.list[index]
          this.$set(obj, 'urgeDisabled', true) // 催一下是否能操作
          this.$set(this.list, index, obj)
        } else {
          this.$message.warn(res.message);
        }
      })
    },
    // 监听路由变化
    getRouteQuery($route) {
      if ($route.params && Object.keys($route.params).length > 0) {
        let params = $route.params
        let projectTitle = process.env.VUE_APP_PLATFORM_NAME
        if (params.type && params.taskId) {
          this.type = params.type
          this.taskId = params.taskId
          this.processId = $route.query.processId
          // console.log("1111111111111")
          // console.log(this.processId)
          document.title = this.getTitle(this.type) + '-审批详情' + ' · ' + projectTitle
          // this.$route.meta.title = this.typeName + '-审批详情' + ' · ' + projectTitle
        }
      }
    },
    // 取字典值
    getTitle(text) {
      return this.$filterDictTextByCache('process_approval_type', text)
    },
    handleCloseCurrentPage() {
      // 注意：以下代码必须存在
      // inject:['closeCurrent'],
      this.closeCurrent()
      this.$router.push({ path: `/examine` })
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-card-head-title) {
  font-weight: bold;
}

.e {
  border-top: 1px #e6e6e6 dashed;
  padding: 25px 0;

  &:first-child {
    border-width: 0;
    padding-top: 0;
  }

  h3 {
    font-weight: bold;
  }
}
</style>
